//
//  PropertyViewController.m
//  YunGui
//
//  Created by wmm on 15/11/10.
//  Copyright © 2015年 hanen. All rights reserved.
//

#import "PropertyViewController.h"
#import "CreatePropertyViewController.h"
#import "PropertyDetailViewController.h"
#import "SideMenuUtil.h"
#import "PropertyCell.h"
#import "SQButton.h"
#import "PropertyModel.h"

#define ROWH 90

@implementation PropertyViewController
{
    UITextField *_searchTF;
    UIView      *_searchView;
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    NSMutableArray  *_bankListArray;
    NSMutableArray  *_bankTypeArray;
    
    int  currentPage;
    
    UIButton  *_selectBtn;
    UIButton  *_selectListBtn;
    UIView * taxisView;
    
    int  btnTag;
}


@synthesize revealController;


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = GrayBackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [SideMenuUtil addViewGesture:self revealController:revealController];
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.title = @"物业管理";
    if(self.isChoose == NO){
        self.navigationItem.leftBarButtonItem=[ViewTool getListBarButtonItemWithTarget:self WithAction:@selector(sideLeftButton_selector:)];
    }else{
        self.navigationItem.leftBarButtonItem=[ViewTool getBackBarButtonItemWithTarget:self WithAction:@selector(goToBack)];
    }
    
    SQButton *btn = [[SQButton alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:20], [UIView getWidth:20])];
    [btn setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    btn.isSelected = NO;
    [btn addTarget:self action:@selector(clickToGetSearch:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.rightBarButtonItem=item;
    
    
    [self createTableView];
    //创建头部视图
    [self createView];
    
    [self initData];//获取银行接口
    [self initBankType];//获取账户类型接口
    
    currentPage = 1;
    //加载数据
    [self initDataWithSearch:@"" withPage:currentPage];
    
    _dataArray = [NSMutableArray array];
    _bankListArray = [NSMutableArray array];
    _bankTypeArray = [NSMutableArray array];
    
}

-(void)viewWillAppear:(BOOL)animated{

    if(_cardDictionary != nil){
        CreatePropertyViewController *createPropertyViewController = [[CreatePropertyViewController alloc] init];
        createPropertyViewController.dictionary = _cardDictionary;
        createPropertyViewController.delegate = self;
        [self.navigationController pushViewController:createPropertyViewController animated:YES];
        _cardDictionary = nil;
    }
}

//AddVisitViewController@protocol UIViewPassValueDelegate
- (void)passValue:(NSString *)value{
    NSLog(@"passValue:%@",value);
    if ([value isEqualToString:@"SUCCESS"]) {
        NSLog(@"^&676");
        [_tableView.mj_header beginRefreshing];
    }
}
- (void)initData{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"app.property.bank.list" forKey:@"method"];
    [dic setObject:@0 forKey:@"isCache"];
    
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dic] success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = jsonDic[@"data"];
        NSMutableArray *arrr = dataDic[@"bankList"];
//        for (int i=0; i<arrr.count; i++) {
//            NSDictionary *dicc = arrr[i];
//            [_bankListArray addObject:dicc[@"bank_name"]];
//        }
        _bankListArray = arrr;
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}
- (void)initBankType{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"app.property.bank.type" forKey:@"method"];
    [dic setObject:@0 forKey:@"isCache"];
    
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dic] success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dataDic = jsonDic[@"data"];
        NSMutableArray *arrr = dataDic[@"bankType"];
        //        NSLog(@"%@--------banktype",arrr);
//        for (int i=0; i<arrr.count; i++) {
//            NSDictionary *dicc = arrr[i];
//            [_bankTypeArray addObject:dicc[@"title"]];
//        }
        _bankTypeArray = arrr;
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)initDataWithSearch:(NSString *)string withPage:(int)page{
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"app.property.list.page" forKey:@"method"];
    [dic setObject:@(page) forKey:@"page"];
    [dic setObject:@10 forKey:@"pageNum"];
    
    if (string.length != 0) {
        
        if ([_selectBtn.currentTitle isEqualToString:@"物业名称"]) {
            [dic setObject:string forKey:@"title"];
        }else if ([_selectBtn.currentTitle isEqualToString:@"城市"]){
            [dic setObject:string forKey:@"city"];
        }else if ([_selectBtn.currentTitle isEqualToString:@"创建人"]){
            [dic setObject:string forKey:@"create_user"];
        }
        
    }
    
    [DataTool postWithUrl:HEAD_URL parameters:[DataTool addSignToDic:dic] success:^(id data) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([jsonDic[@"status"] isEqualToString:@"ERROR"]) {
            [Tools showMessage:jsonDic[@"msg"] view:self];
            
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            return ;
        }else{
        id dd = [DataTool changeType:jsonDic];
        NSDictionary *dataDic = dd[@"data"];
        NSMutableArray *array = dataDic[@"listData"];
        for (int i=0; i<array.count; i++) {
            PropertyModel *model = [[PropertyModel alloc]init];
             [model setValuesForKeysWithDictionary:array[i]];
            [_dataArray addObject:model];
        }
        [_tableView reloadData];
        [_tableView.mj_header endRefreshing];
            int total = [dataDic[@"total"] intValue];
            if (total <= 10) {
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }else{
                if (array.count < 10) {
                    [_tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [_tableView.mj_footer endRefreshing];
                }
            }
            
        }
        NSLog(@"sdjskljlkjgldjkklfkdl");
        NSLog(@"%@+--++--++-",jsonDic);
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
        [Tools showMessage:error.localizedDescription view:self];
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];

    }];
    
}
//创建头部视图
-(void)createView
{
    CGFloat searchH = 60 + 15;
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, searchH)];
    _searchView.hidden = YES;
    [self.view addSubview:_searchView];
    
    UIView *searchV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    [searchV setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"Btn_Normal_Sousuodi.png"]]];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10, searchV.width-40, searchV.height - 2*10)];
    imgView.image = [UIImage imageNamed:@"Btn_Normal_Sousuokuang.png"];
    [searchV addSubview:imgView];
    
    [_searchView addSubview:searchV];
    UIView *bg = [[UIView alloc]initWithFrame:CGRectMake(0, searchV.maxY, kScreenWidth, 15)];
    bg.backgroundColor = GrayBackColor;
    [_searchView addSubview:bg];
    
    UIView *line11 = [ViewTool getLineViewWith:CGRectMake(0, bg.maxY -1, kScreenWidth, 1) withBackgroudColor:UIColorFromRGB(0xe6e7eb)];
    [_searchView addSubview:line11];
    
    _selectBtn = [self getButtonWithFrame:CGRectMake(imgView.x+5, imgView.y+0, 70, 40) withTitle:@"物业名称"];
//    _selectBtn.backgroundColor = [UIColor redColor];
    _selectBtn.tag = 0;
    [_selectBtn addTarget:self action:@selector(showSelectList:) forControlEvents:UIControlEventTouchUpInside];
    _selectBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_selectBtn setTitleColor:UIColorFromRGB(0xa1a2a7) forState:UIControlStateNormal];
    _selectBtn.titleLabel.font = [ViewTool getFont:16.0f];
    [searchV addSubview:_selectBtn];
    
    _selectListBtn = [ViewTool getButtonImgWithTarget:self withFrame:CGRectMake(_selectBtn.maxX, imgView.y+12.5, 15, 15) WithString:@"Btn_Normal_Gengduo" WithAction:@selector(showSelectList:)];
    [searchV addSubview:_selectListBtn];
    
    UIView *line = [ViewTool getLineViewWith:CGRectMake(_selectListBtn.maxX+5, _selectListBtn.y-2.5, 1, imgView.height-2*10) withBackgroudColor:LEFTLINECOLOR];
    [searchV addSubview:line];
    
    _searchTF = [[UITextField alloc]initWithFrame:CGRectMake(line.x + 5, imgView.y  , imgView.maxX - line.x -5, imgView.height)];
//    _searchTF.backgroundColor = [UIColor redColor];
    _searchTF.delegate = self;
    _searchTF.placeholder = @"物业名称/城市/创建人";
    _searchTF.returnKeyType = UIReturnKeySearch;
    _searchTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [_searchTF setValue:LEFTLINECOLOR forKeyPath:@"_placeholderLabel.textColor"];
    [_searchTF setValue:[UIFont systemFontOfSize:16.0f] forKeyPath:@"_placeholderLabel.font"];
    [searchV addSubview:_searchTF];
    
    UIButton *addBtn = [ViewTool getAddButtonWithTarget:self WithString:@"add.png" WithAction:@selector(goToCreateProperty:)];
    [self.view addSubview:addBtn];
    [self.view bringSubviewToFront:addBtn];
    
    [self addTaxisView];    
}
- (void)hideSearchButton{
    if (_searchTF.text == nil || _searchTF.text.length == 0) {
        [Tools showMessage:@"请输入搜索关键字" view:self];
        return;
    }
    [_searchTF resignFirstResponder];
    currentPage = 1;
    [_dataArray removeAllObjects];
    
    [self initDataWithSearch:_searchTF.text withPage:currentPage];
}
- (void)showSelectList:(UIButton *)sender{
    if (sender.tag == 0) {
        if (taxisView.hidden) {
            taxisView.hidden = NO;
        }else{
            taxisView.hidden = YES;
        }
    }else{
        UIButton *btn = [taxisView viewWithTag:btnTag];
        [btn setTitleColor:UIColorFromRGB(0xa1a2a7) forState:UIControlStateNormal];
        
        [sender setTitleColor:YELLOWBTNCOLOR forState:UIControlStateNormal];
        btnTag = (int)sender.tag;
        
        taxisView.hidden = YES;
        [_selectBtn setTitle:sender.currentTitle forState:UIControlStateNormal];
    }
}
- (void)addTaxisView{
    
    NSArray *titleArr = @[@"物业名称",@"城市",@"创建人"];
    CGFloat btnH = 40;
    CGFloat taxisW = 130;
    taxisView = [[UIView alloc]initWithFrame:CGRectMake(20, _searchView.maxY -15, taxisW, titleArr.count * btnH+10)];
    taxisView.hidden = YES;
    
    UIImageView *bgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, taxisView.width, taxisView.height)];
    bgView.image = [UIImage imageNamed:@"Btn_Normal_Shaixuan.png"];
    [taxisView addSubview:bgView];
    [self.view addSubview:taxisView];
    
    for (int i= 0; i < titleArr.count; i++) {
        UIButton *btn = [self getButtonWithFrame:CGRectMake(10, 5+btnH*i, taxisView.width, btnH) withTitle:titleArr[i]];
        btn.tag = 112233 + i;
        [btn addTarget:self action:@selector(showSelectList:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = [ViewTool getFont:16.0f];
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [taxisView addSubview:btn];
        
        UIView *lineview = [ViewTool getLineViewWith:CGRectMake(0, 5+btnH*(i+1)-1, taxisView.width, 1) withBackgroudColor:DARKGRAYLINECOLOR];
        [taxisView addSubview:lineview];
        
        if (i == titleArr.count -1) {
            [lineview removeFromSuperview];
        }
    }
    
    btnTag = 112233;
    UIButton *btn = [taxisView viewWithTag:btnTag];
    [btn setTitleColor:YELLOWBTNCOLOR forState:UIControlStateNormal];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    if(textField.text.length != 0){
        [_dataArray removeAllObjects];
        currentPage = 1;
        [self initDataWithSearch:textField.text withPage:currentPage];
    }
    return YES;
}

- (UIButton *)getButtonWithFrame:(CGRect)frame withTitle:(NSString *)title {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:UIColorFromRGB(0xa1a2a7) forState:UIControlStateNormal];
    [button setTitleColor:YELLOWBTNCOLOR forState:UIControlStateHighlighted];
    button.titleLabel.font= [UIFont systemFontOfSize:16.0f];
    return button;
}

-(void)createTableView
{
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64) style:UITableViewStylePlain];
    _tableView.rowHeight = ROWH;
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = GrayBackColor;
    [self.view addSubview:_tableView];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self loadNewData];
    }];
    
    // 马上进入刷新状态
    [_tableView.mj_header beginRefreshing];
    
    // 上拉刷新
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            currentPage++;
            if (_searchTF.text.length != 0) {
                
                [self initDataWithSearch:_searchTF.text withPage:currentPage];
            }else{
                
            [self initDataWithSearch:@"" withPage:currentPage];
                
            }
        });
    }];

}
- (void)loadNewData{
    
    [_dataArray removeAllObjects];
    currentPage = 1;
    [self initDataWithSearch:_searchTF.text withPage:currentPage];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (taxisView.hidden == NO) {
        taxisView.hidden = YES;
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    if (taxisView.hidden == NO) {
        taxisView.hidden = YES;
    }
}

//跳到创建物业界面
- (void)goToCreateProperty:(UIButton *)btn
{
    CreatePropertyViewController * propertyVC=[[CreatePropertyViewController alloc]init];
//    propertyVC.bankListArr = _bankListArray;
//    propertyVC.bankTypeArr = _bankTypeArray;
    propertyVC.delegate = self;
    [self.navigationController pushViewController:propertyVC animated:NO];
}


#pragma mark
#pragma mark---协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"cell";
    PropertyCell * cell=[tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell=[[PropertyCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    if (_dataArray.count > 0) {
        PropertyModel *model = _dataArray[indexPath.row];
    
    cell.companyLab.text = model.title;
    
    NSString *strr = model.created_at;
    if ([strr isEqualToString:@"-"]) {
        cell.timeLab.text = @"";
        cell.dateLab.text = @"";
    }else{
//        NSDateFormatter *format = [[NSDateFormatter alloc]init];
//        [format setDateFormat:@"yyyy/MM/dd"];
//        NSDate *date = [format dateFromString:strr];
//        NSString *dateStr = [format stringFromDate:date];
//        NSString *weekStr = [self weekdayStringFromDate:date];
        NSString *yearStr = [strr substringWithRange:NSMakeRange(0, 4)];
        NSString *monthStr = [strr substringWithRange:NSMakeRange(5, 2)];
        NSString *dayStr = [strr substringWithRange:NSMakeRange(8, 2)];
        
        NSString *timeStr = [strr substringWithRange:NSMakeRange(11, 5)];
        cell.timeLab.text = timeStr;
        cell.dateLab.text = [NSString stringWithFormat:@"%@/%@/%@",yearStr,monthStr,dayStr];
    }
    
    cell.crePerLab.text = [NSString stringWithFormat:@"创建人:%@",model.realname];
    
    if ([model.province isEqualToString:model.city]) {
        cell.addressLab.text = [NSString stringWithFormat:@"所在地:%@",model.city];;
    }else{
        cell.addressLab.text = [NSString stringWithFormat:@"所在地:%@ %@",model.province,model.city];
    }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isChoose) {
         PropertyModel *model = _dataArray[indexPath.row];
        
        if ([self.delegate respondsToSelector:@selector(backTolastView:)]) {
            [self.delegate backTolastView:model];
        }
        [self.navigationController popViewControllerAnimated:NO];
        
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        PropertyModel *model = _dataArray[indexPath.row];
        PropertyDetailViewController * vc=[[PropertyDetailViewController alloc]init];
        vc.proId = model.propertyId;
        vc.bankListArr = _bankListArray;
        vc.bankTypeArr = _bankTypeArray;
        [self.navigationController pushViewController:vc animated:YES];
    }
   
}
- (void)clickToGetSearch:(SQButton *)btn{
    if (taxisView.hidden == NO) {
        taxisView.hidden = YES;
    }
    
    if (btn.isSelected == NO) {
        
        _searchView.hidden = NO;
        _tableView.frame = CGRectMake(0, _searchView.height, kScreenWidth, kScreenHeight-64 -_searchView.height);
        
        btn.isSelected = YES;
    }else{
        
        _searchView.hidden = YES;
        _tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-64);
       
        btn.isSelected = NO;
    }
    
}
//传入的日期得到星期几
- (NSString*)weekdayStringFromDate:(NSDate*)inputDate {
    
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}
- (void)goToBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (taxisView.hidden == NO) {
        taxisView.hidden =YES;
    }
    
}
// 拉开左侧:点击.
- (void)sideLeftButton_selector:(id)sender {
    [self.revealController toggleSidebar:!self.revealController.sidebarShowing duration:kGHRevealSidebarDefaultAnimationDuration];
}

@end
